﻿using LuaInterface;
using UnityEngine;
using UnityEngine.UI;

namespace Framework.UGUI
{
	public class InputFieldWrap : MonoBehaviour
	{
		public static InputFieldWrap Get(GameObject go)
		{
			InputField inputField = go.GetComponent<InputField>();
			if (inputField != null)
			{
				return go.OnceAddComponent<InputFieldWrap>();
			}
			return null;
		}

		public static InputFieldWrap GetWithPath(GameObject go, string path)
		{
			var inputFieldTransform = go.transform.Find(path);
			if (inputFieldTransform != null)
			{
				return Get(inputFieldTransform.gameObject);
			}
			return null;
		}

		private InputField _inputField;
		public InputField inputField
		{
			get
			{
				if (_inputField == null)
				{
					_inputField = gameObject.GetComponent<InputField>();
				}
				return _inputField;
			}
		}

		private GeneralCallBack _onValueChangedCallback;
		private GeneralCallBack _onEndEditCallback;

		public void AddOnValueChanged(LuaFunction onValueChanged, LuaTable onValueChangedTarget)
		{
			GeneralCallBack.GetOrReUse(ref _onValueChangedCallback, onValueChanged, onValueChangedTarget);
			inputField.onValueChanged.RemoveListener(OnValueChanged);
			inputField.onValueChanged.AddListener(OnValueChanged);
		}

		public void RemoveOnValueChanged()
		{
			_clearValueChangedCallback();
			inputField.onValueChanged.RemoveListener(OnValueChanged);
		}

		public void AddOnEndEdit(LuaFunction onEndEdit, LuaTable onEndEditTarget)
		{
			GeneralCallBack.GetOrReUse(ref _onEndEditCallback, onEndEdit, onEndEditTarget);
			inputField.onEndEdit.RemoveListener(OnEndEdit);
			inputField.onEndEdit.AddListener(OnEndEdit);
		}

		public void RemoveOnEndEdit()
		{
			_clearOnEndEditCallback();
			inputField.onEndEdit.RemoveListener(OnEndEdit);
		}

		public string GetText()
		{
			return inputField.text;
		}

		public void SetText(string text)
		{
			inputField.text = text;
		}

		public void SetCharacterLimit(int characterLimit)
		{
			if (characterLimit > 0)
			{
				inputField.characterLimit = characterLimit;
			}
		}

		private void OnValueChanged(string text)
		{
			if (_onValueChangedCallback != null)
			{
				GeneralCallBack.Invoke(ref _onValueChangedCallback, text);
			}
		}

		private void _clearValueChangedCallback()
		{ 
			GeneralCallBack.RecycleInst(ref _onValueChangedCallback); 
		}

		private void OnEndEdit(string text)
		{
			if (_onEndEditCallback != null)
			{
				GeneralCallBack.Invoke(ref _onEndEditCallback, text);
			}
		}

		private void _clearOnEndEditCallback()
		{
			GeneralCallBack.RecycleInst(ref _onEndEditCallback);
		}

		void OnDestroy()
		{
			if (_onValueChangedCallback != null)
			{ 
				UIEventDebugger.LogUIEventError("InputFieldWrap.onValueChanged", gameObject); 
			}
			if (_onEndEditCallback != null)
			{
				UIEventDebugger.LogUIEventError("InputFieldWrap.onEndEdit", gameObject);
			}
			_clearOnEndEditCallback();
			_clearValueChangedCallback();
		}
	}
}